<template>
  <div class="create-cost-dialog">
    <!-- 新增编辑成本 开始 -->
    <el-dialog
      :visible.sync="dialogVisible"
      :append-to-body="false"
      :class="{'mobile-el-dialog': showMobilePage}"
      class="dialog-size-auto small-common-dialog-size"
      width="450px"
      @close="handleClose">
      <div :class="{'mobile-create-cost' : showMobilePage}" class="main">
        <div :style="{maxHeight: maxHeight}" class="cost-form-box">
          <div v-if="isEdit && linkIncomeItemNo" class="income-form-box">
            <Title title="关联收入项" font-size="16px" style="margin-bottom: 16px" />
            <el-form ref="formRef" :model="incomeData" :label-width="labelWidth" :label-position="formAlign">
              <el-row>
                <el-col>
                  <el-form-item label="收入项" prop="incomeItemId">
                    <el-select v-model="incomeData.incomeItemName" disabled size="small" class="width240" />
                  </el-form-item>
                </el-col>
                <el-col>
                  <el-form-item label="收入细项" prop="incomeDetail">
                    <el-select v-model="incomeData.incomeDetail" disabled size="small" class="width240" />
                  </el-form-item>
                </el-col>
                <el-col>
                  <el-form-item label="单价" prop="unitPrice">
                    <el-input v-model="incomeData.unitPrice" disabled type="number" size="small" class="width240" />
                  </el-form-item>
                </el-col>
                <el-col>
                  <el-form-item label="数量" prop="number">
                    <el-input v-model="incomeData.number" disabled type="number" size="small" class="width240" />
                  </el-form-item>
                </el-col>
                <el-col>
                  <el-form-item label="总价" prop="totalPrice">
                    <el-input v-model="incomeData.totalPrice" disabled type="number" size="small" class="width240" />
                  </el-form-item>
                </el-col>
                <el-col>
                  <el-form-item label="税率" prop="taxRate">
                    <el-input
                      v-model="incomeData.taxRate"
                      :maxlength="12"
                      disabled
                      class="width240"
                      placeholder="请输入内容"
                      size="small"
                    >
                      <span slot="suffix">%</span>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col>
                  <el-form-item label="交付时间">
                    <el-date-picker
                      v-model="incomeData.deliverTime"
                      :clearable="true"
                      type="date"
                      disabled
                      class="width240"
                      placeholder="请选择交付时间"
                      value-format="timestamp"
                      format="yyyy/MM/dd"
                      size="small"/>
                  </el-form-item>
                </el-col>
                <el-col>
                  <el-form-item label="业绩月份">
                    <el-date-picker
                      v-model="incomeData.month"
                      :clearable="true"
                      disabled
                      type="month"
                      class="width240"
                      placeholder="请选择业绩月份"
                      value-format="timestamp"
                      size="small"
                      format="yyyy/MM"/>
                  </el-form-item>
                </el-col>
                <el-col>
                  <el-form-item label="款项应收时间">
                    <el-date-picker
                      v-model="incomeData.receivableTime"
                      :clearable="true"
                      type="date"
                      disabled
                      class="width240"
                      placeholder="请选择款项应收时间"
                      value-format="timestamp"
                      format="yyyy/MM/dd"
                      size="small"/>
                  </el-form-item>
                </el-col>
                <el-col>
                  <el-form-item label="分期月份">
                    <el-date-picker
                      v-model="incomeData.incomeTimeRange"
                      type="monthrange"
                      size="small"
                      class="width240"
                      disabled
                      range-separator="-"
                      value-format="timestamp"
                      start-placeholder="开始月份"
                      end-placeholder="结束月份"
                      format="yyyy/MM"/>
                  </el-form-item>
                </el-col>
                <el-col>
                  <el-form-item label="说明">
                    <el-input
                      v-model="incomeData.explain"
                      :height="60"
                      disabled
                      placeholder="请输入说明"
                      style="font-size: 13px;"
                      type="textarea"
                      size="small"
                      resize="none"
                      maxlength="200"
                      class="width240"/>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>
          <div class="form-box">
            <Title :title="!isEdit?'添加成本':'编辑成本'" font-size="16px" style="margin-bottom: 16px" />
            <el-form
              ref="costDataForm"
              :rules="rules"
              :model="queryData"
              :label-width="labelWidth"
              :label-position="formAlign"
              class="lineHeight32">
              <el-form-item label="成本来源" prop="costBelong">
                <el-select
                  v-model="queryData.costBelong"
                  :disabled="isEdit || costBelongType > -1"
                  popper-class="global-select-down"
                  name="costBelong"
                  class="width240"
                  size="small"
                  @change="getCostList">
                  <el-option
                    v-for="item in belongOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value" />
                </el-select>
              </el-form-item>
              <el-form-item label="成本项" prop="costItemId">
                <el-select
                  v-model="queryData.costItemId"
                  :disabled="(queryData.isAutoCreate || !!linkIncomeItemNo) && isEdit"
                  popper-class="global-select-down"
                  name="costItemId"
                  class="width240"
                  size="small"
                  @change="setCostItem">
                  <el-option
                    v-for="item in costItemOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value" />
                </el-select>
              </el-form-item>
              <el-form-item class="label-999" label="成本类型:" prop="costType">
                <span v-if="selectCostItem.costType || selectCostItem.costType === 0">{{ selectCostItem.costType | costTypeFilter }}</span>
                <span v-else>--</span>
                <span v-if="selectCostItem.costType === 5">
                  <el-switch
                    v-model="queryData.autoCost"
                    :active-value="1"
                    :inactive-value="0"
                    class="fb-switch"/>
                  <span class="text">{{ autoCost ?'自动':'手动' }}计算成本</span>
                </span>
              </el-form-item>
              <el-form-item label="申请人" prop="proposer">
                <selectWithUserLoad
                  v-if="flag"
                  ref="proposerRef"
                  :extend-params="{
                    type: 1,
                  }"
                  v-model="queryData.proposerObj"
                  :hide-select-list="defaultProposer"
                  :multiple="false"
                  :is-no-loading="true"
                  show-check-user
                  value-type="object"
                  key-name="id"
                  class="width240"
                  label-name="userName"
                  filterable
                />
              </el-form-item>
              <el-form-item v-if="selectCostItem.costType === 1" label="平台ID" prop="platId">
                <el-input
                  v-model="queryData.platId"
                  type="text"
                  size="small"
                  maxlength="32"
                  class="width240"/>
              </el-form-item>
              <el-form-item v-if="selectCostItem.costType !== 4" label="含税成本(元)" prop="taxCost">
                <el-input
                  v-model="queryData.taxCost"
                  :disabled="autoCost"
                  name="taxCost"
                  placeholder="请输入金额"
                  type="text"
                  size="small"
                  class="width240"
                  @blur="numberInputChange"
                  @input="taxCostChange">
                  <div v-if="autoCost && isEdit" slot="suffix" class="formula">
                    <el-tooltip placement="top" effect="dark">
                      <div slot="content" class="max-width-300">
                        <div class="mb5">供应商：{{ queryData.supplierName || '--' }}</div>
                        <template v-if="queryData.talentOptions">
                          <div v-if="queryData.talentOptions.ruleName" class="mb5">{{ queryData.talentOptions.ruleName || '' }}</div>
                          <div class="mb5">公式：{{ queryData.talentOptions.formula || '--' }}</div>
                          <div>条件：{{ queryData.talentOptions.condition || '--' }}</div>
                        </template>
                      </div>
                      <div class="fx-icon">
                        <img :src="fxIcon" alt="公式计算">
                      </div>
                    </el-tooltip>
                  </div>
                </el-input>
              </el-form-item>
              <el-form-item label="供应商" prop="supplierId">
                <selectWithoutHttp
                  v-if="!pageFromMengli"
                  v-model="queryData.supplierId"
                  :list-data="supplierList"
                  :disabled="autoCost"
                  :item-max-width="240"
                  :clearable="true"
                  visible-change-data
                  class="width240"
                  label-name="value"
                  extend-class="order-client-select"
                  key-name="id"
                  filterable
                  placeholder="请选择"
                  add-new
                  add-new-str="添加新供应商"
                  @change="supplierIdChange"
                  @addNewClick="toCreateSupplier"
                  @clear="clearSupplier" />
                <MengliSuppliersLoad v-else ref="mengliSuppliersLoad" :is-auto-create="queryData.isAutoCreate" :is-edit="isEdit" :options="selectSupplierItem" class="width240" @mengliSuppliersChange="supplierIdChange"/>
              </el-form-item>
              <el-form-item label="可抵扣税率" prop="deductionRate">
                <el-input
                  v-model="queryData.deductionRate"
                  :disabled="autoCost || queryData.autoDeductionRate === 1"
                  :style="showMobilePage?'width:100px;':''"
                  type="text"
                  size="small"
                  class="width140"
                  @input="deuctiomRateInput">
                  <span slot="suffix" class="deductionRate">%</span>
                </el-input>
                <el-switch
                  v-model="queryData.autoDeductionRate"
                  :active-value="1"
                  :inactive-value="0"
                  class="fb-switch"
                  @change="autoDeductionRateChange"/>
                <span class="text">{{ queryData.autoDeductionRate ?'自动':'手动' }}</span>
              </el-form-item>
              <!-- <el-form-item v-if="pageFromMengli && selectCostItem.costType === 4" label="分成比例" prop="dividePercent">
                <el-input
                  v-model="queryData.dividePercent"
                  :disabled="queryData.isAutoCreate && isEdit"
                  type="text"
                  size="small"
                  class="width240"
                  @input="dividePercentChange">
                  <span slot="suffix" class="deductionRate">%</span>
                </el-input>
              </el-form-item> -->
              <el-form-item v-if="pageFromMengli && selectCostItem.costType === 4" label="分成金额" prop="sharingPrice">
                <el-input
                  v-model="queryData.sharingPrice"
                  :disabled="true"
                  type="text"
                  size="small"
                  class="width240"/>
              </el-form-item>
              <el-form-item label="说明" prop="costDescription" style="padding-bottom: 2px;">
                <el-input
                  v-model="queryData.costDescription"
                  :height="60"
                  type="textarea"
                  size="small"
                  maxlength="100"
                  placeholder="最多100个字符"
                  class="width240"/>
              </el-form-item>
              <el-form-item v-if="linkIncomeItemNo" label="分成比例">
                <el-input
                  v-model="queryData.dividePercent"
                  :style="showMobilePage?'width:100px;':''"
                  :disabled="!!autoDividePercent"
                  type="text"
                  size="small"
                  class="width140"
                  @input="dividePercentInput"
                  @blur="numberInputChange">
                  <span slot="suffix" class="deductionRate">%</span>
                </el-input>
                <el-switch
                  v-model="autoDividePercent"
                  :active-value="1"
                  :inactive-value="0"
                  class="fb-switch"
                  @change="autoDividePercentChange"/>
                <span class="text">{{ autoDividePercent ?'自动':'手动' }}</span>
              </el-form-item>
            </el-form>
          </div>
        </div>
        <div class="btn-container">
          <el-button :loading="btnLoading" type="primary" size="small" @click="handleOk">确定</el-button>
          <el-button class="cancel-btn-style" size="small" style="width: 80px" @click="handleClose()">取消</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapState } from 'vuex';
import { hasRouteAuth } from '@/utils/permission';
import ElMessage from '@/utils/message';
// 组件
import Title from '@/components/Title';
import selectWithoutHttp from '@/components/Common/selectWithoutHttp';
import MengliSuppliersLoad from '@/components/Mengli/MengliSuppliersLoad';
import selectWithUserLoad from '@/components/Common/selectWithUserLoad';
// api
import { createCost, editCost, getCostDetail } from '@/api/costManage';
import { costList } from '@/api/config';
import { channelList } from '@/api/select';
import { getRelatedIncome } from '@/api/mengliOrder';
import { costTypeFilter } from '@/filters/status';
import { percentRate, taxCost } from '@/utils/numFormat';
import { costBelong } from '@/views/cost/model/selectData';
import mobileCreate from '@/mixins/mobileCreate';
import fxIcon from '@/assets/fx.png';

export default {
  name: 'CreateEditCost',
  components: {
    Title,
    selectWithoutHttp,
    selectWithUserLoad,
    MengliSuppliersLoad },
  filters: { costTypeFilter },
  mixins: [mobileCreate],
  props: {
    // edit代表编辑，默认新增
    type: {
      type: String,
      default: ''
    },
    // 关联订单的id
    relatedOrderId: {
      type: Number | String,
      default: 0
    },
    // 成本id
    costId: {
      type: Number,
      default: 0
    },
    // 从哪个页面打开 pageFrom:mengli 代表萌力新增 orderCreateEdit：渠道订单-新建/编辑
    pageFrom: {
      type: String,
      default: ''
    },
    // 只返回表单数据，不在组件内请求新建编辑成本接口
    onlyReturnFormData: {
      type: Boolean,
      default: false
    },
    // 是否在封账页面编辑成本
    isFromSealing: {
      type: Boolean,
      default: false
    },
    // 填充的成本数据
    costData: {
      type: Object,
      default: () => {}
    },
    // 成本来源类型
    // 用于如果是详情页内新增自动固定来源
    // 默认不填
    costBelongType: {
      type: Number,
      default: -1
    },
    // 是否是萌力订单中成本列表的新建、编辑成本
    isMengliDetailCost: {
      type: Boolean,
      default: false
    }
  },
  data() {
    const validateStr = (msg, attr) => {
      return (rule, value, callback) => {
        const str = this.queryData[attr];
        if (!str && str !== 0) { callback(new Error(msg)); } else { callback(); }
      };
    };
    return {
      fxIcon,
      rules: {
        costBelong: [{ required: true, trigger: 'blur', validator: validateStr('请选择成本来源', 'costBelong') }],
        costItemId: [{ required: true, trigger: 'blur', validator: validateStr('请选择成本项', 'costItemId') }],
        dividePercent: [{ required: true, trigger: 'blur', validator: validateStr('请填写分成比例', 'dividePercent') }],
        supplierId: [{ required: true, trigger: 'blur', validator: validateStr('请选择供应商', 'supplierId') }]
      },
      queryData: {
        autoCost: 0,
        costBelong: '',
        autoDeductionRate: 1,
        deductionRate: '',
        taxCost: '',
        costDescription: '',
        supplierId: '',
        platId: '',
        costType: '',
        dividePercent: '',
        talentOptions: {},
        proposerObj: {}
      },
      autoDividePercent: 1,
      defaultProposer: [], // 默认申请人
      isEdit: false,
      dialogVisible: false,
      btnLoading: false,
      costItemOptions: [],
      selectCostItem: {},
      selectSupplierItem: {},
      mengliBelongOptions: [
        { label: '商务订单', value: 2 },
        { label: '营销授权', value: 3 }
      ],
      otherBelongOptions: [
        { label: '渠道订单', value: 0 }
      ],
      belongOptions: [],
      supplierList: [],
      supplierId: '',
      deductionRate: '',
      newDeductionRate: null,
      flag: true,
      linkIncomeItemNo: null, // 关联收入项
      incomeData: {
        incomeItemName: '',
        incomeDetail: '',
        unitPrice: null,
        number: null,
        totalPrice: null,
        taxRate: null,
        deliverTime: '',
        month: '',
        receivableTime: '',
        incomeTimeRange: '',
        explain: ''
      },
      maxHeight: ''
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo,
      'showMobilePage': state => state.app.showMobilePage
    }),
    isAdmin() {
      return this.userInfo.userName === '管理员';
    },
    // 自动设置成本金额并且类型为公式计算
    autoCost() {
      return this.queryData.autoCost === 1 && this.selectCostItem.costType === 5;
    },
    // 萌力页面打开或者成本类型为分成比例
    pageFromMengli() {
      return this.pageFrom === 'mengli';
    },
    labelWidth() {
      return this.showMobilePage ? '90px' : '110px';
    }
  },
  watch: {
    async type(newVal) {
      this.flag = false;
      this.$nextTick(() => {
        this.flag = true;
      });
      this.isEdit = this.type === 'edit';
      // 编辑区分是否需要请求成本详情接口，有costId并且costData为空并且是编辑的状态要请求成本详情接口
      if (this.isEdit && (!this.costData || (this.costData && !this.costData.id)) && this.costId) {
        this.getCostDetail();
      } else if (this.isEdit && this.costData) {
        this.queryData = { ...this.costData };
        await this.getCostList(this.queryData.costBelong);
        const proposerObj = {// 3.0.2新增申请人
          id: this.costData.proposerId,
          userName: this.costData.proposer
        };
        this.defaultProposer = [{
          id: this.costData.proposerId,
          userName: this.costData.proposer
        }];
        this.setMoneyData(this.queryData);
        this.setSelectData();
        this.$set(this.queryData, 'proposerObj', proposerObj);
        if (this.queryData.id) {
          this.getRelatedIncome(this.queryData.id);
        }
        this.$forceUpdate();
      }
    }
  },
  created() {
    this.setData();
    if (!this.pageFromMengli) {
      this.channelList();
    }
  },
  methods: {
    hasRouteAuth,
    handleClose() {
      this.$refs.costDataForm.clearValidate();
      this.dialogVisible = false;
      this.resetData();
      this.$emit('handleClose', '');
    },
    async openDialog(row) {
      if (typeof row === 'number') {
        await this.getCostList(row);
      }
      const clientHeight = window.innerHeight;
      this.maxHeight = (clientHeight * 2.8) / 5 + 'px';
      this.dialogVisible = true;
      if (row && typeof row !== 'number') this.linkIncomeItemNo = row.linkIncomeItemNo || '';
      if (this.queryData.dividePercent) this.queryData.dividePercent = row.dividePercent;
      if (!this.isEdit) {
        this.defaultProposer = [{
          id: this.userInfo.id,
          userName: this.userInfo.userName
        }];
        this.$set(this.queryData, 'proposerObj', { id: this.userInfo.id, userName: this.userInfo.userName });
      }
      this.setData();
    },
    numberInputChange() {
      if (this.queryData.taxCost === '-') {
        this.queryData.taxCost = 0;
      }
      if (this.linkIncomeItemNo) {
        // 总价=含税成本/分成比例*(1+税率)
        this.incomeData.totalPrice = (this.queryData.taxCost / (this.queryData.dividePercent ? this.queryData.dividePercent / 100 : 1) * (1 + this.incomeData.taxRate / 100)).toFixed(2);
        this.incomeData.unitPrice = (this.incomeData.totalPrice / this.incomeData.number).toFixed(2);
      }
    },
    // 获取关联收入项
    getRelatedIncome(id) {
      getRelatedIncome({ id }).then(res => {
        if (res.data) {
          this.incomeData = res.data;
          const { incomeStartTime, incomeEndTime } = this.incomeData;
          if (incomeStartTime && incomeEndTime) {
            this.$set(this.incomeData, 'incomeTimeRange', [incomeStartTime, incomeEndTime]);
          }
        }
      }).catch(err => console.error(err.message));
    },
    // 设置默认获取的数据
    setData() {
      this.queryData.relatedOrderId = this.relatedOrderId;
      this.setCostBelongType();
    },
    // 设置选中下拉的名称
    setSelectData() {
      // const { costType, costItemName, supplierName, supplierId, deductionRate } = this.queryData;
      // this.selectCostItem.costType = costType;
      // this.selectCostItem.costItemName = costItemName;
      // this.selectCostItem.costName = costItemName;
      const { deductionRate, supplierId, supplierName, costItemId } = this.queryData;
      this.setCostItem(costItemId);
      // 萌力的供应商和渠道的供应商不一样
      this.$set(this.selectSupplierItem, 'value', supplierName);
      this.$set(this.selectSupplierItem, 'keyword', supplierName);
      this.$set(this.selectSupplierItem, 'supplier', supplierName);
      this.$set(this.selectSupplierItem, 'id', supplierId);
      this.supplierId = supplierId;
      this.deductionRate = deductionRate;
    },
    // 设置成本来源选项
    setCostBelongType() {
      if (this.costBelongType !== -1) {
        const costBelongItem = costBelong.find(i => i.value === this.costBelongType);
        if (costBelongItem) {
          this.belongOptions = [costBelongItem];
          this.queryData.costBelong = this.belongOptions[0].value;
          this.getCostList(this.belongOptions[0].value);
        }
        // this.belongOptions = [costBelongItem];
        return false;
      }
      this.belongOptions = this.pageFromMengli ? this.mengliBelongOptions : this.otherBelongOptions;
    },
    // 金额处理分转元
    setMoneyData(data = {}) {
      const { taxCost: taxCostMoney, sharingPrice, dividePercent } = data;
      data.taxCost = !taxCostMoney ? taxCostMoney : this.showPrecise(taxCostMoney / 100);
      data.dividePercent = !dividePercent ? dividePercent : this.showPrecise(dividePercent * 100);
      data.sharingPrice = !sharingPrice ? sharingPrice : this.showPrecise(sharingPrice / 100);
    },
    // 精度处理
    showPrecise(num, precision = 12) {
      // 适用于长数值的直接展示 不适用于 两个浮点数的计算
      return +parseFloat(num.toPrecision(precision));
    },
    editItem(item) {
      if (this.$refs.costDataForm) this.$refs.costDataForm.clearValidate(); // 清空校验
      this.queryData = JSON.parse(JSON.stringify(item));
      this.dialogVisible = true;
    },
    addItem() {
      this.dialogVisible = true;
      if (this.$refs.costDataForm) this.$refs.costDataForm.clearValidate();// 清空校验
    },
    handleOk() {
      const paramsObj = JSON.parse(JSON.stringify(this.queryData));
      if (paramsObj.proposerObj) {
        paramsObj.proposerId = paramsObj.proposerObj.id;
        paramsObj.proposer = paramsObj.proposerObj.userName;
      }
      if (this.userInfo.deptName && this.userInfo.deptName.length) {
        paramsObj.departmentId = this.userInfo.deptName.map(i => i.id).join(',');
      }
      // 来源为萌力的页面关联订单类型为2
      paramsObj.relatedOrderType = this.pageFromMengli ? 2 : 0;
      paramsObj.supplierId = this.selectSupplierItem.id;
      delete paramsObj.talentOptions;
      this.$refs.costDataForm.validate(valid => {
        if (valid) {
          if (Number(paramsObj.taxCost) === 0 && !this.selectCostItem.canBeZero) {
            ElMessage.error('含税成本不能为0');
            return;
          }
          if (this.selectCostItem.canBeZero && paramsObj.taxCost !== 0 && !paramsObj.taxCost) {
            ElMessage.error('含税成本不能为空');
            return;
          }
          if (!this.onlyReturnFormData) {
            paramsObj.taxCost = paramsObj.taxCost ? Math.round(paramsObj.taxCost * 100) : paramsObj.taxCost;
            paramsObj.dividePercent = paramsObj.dividePercent ? paramsObj.dividePercent / 100 : paramsObj.dividePercent;
            this.isEdit ? this.edit(paramsObj) : this.add(paramsObj);
          } else {
            paramsObj.supplierName = this.selectSupplierItem.value;
            paramsObj.costItemName = this.selectCostItem.costName;
            paramsObj.costType = this.selectCostItem.costType;
            this.$emit('submit', paramsObj);
            this.handleClose();
          }
        } else {
          return false;
        }
      });
    },
    // 获取成本详情
    getCostDetail() {
      const params = { costId: this.costId };
      getCostDetail(params).then(res => {
        if (res.data) {
          if (res.data && res.data.autoDeductionRate) {
            res.data.deductionRate = this.formatDeductionRate(res.data.supplierId);
          }
          this.defaultProposer = [{
            id: res.data.proposerId,
            userName: res.data.proposer
          }];
          const proposerObj = {// 3.0.2新增申请人
            id: res.data.proposerId,
            userName: res.data.proposer
          };
          this.setMoneyData(res.data);
          if (res.data.costItemId) {
            this.selectCostItem = this.costItemOptions.find(i => i.costId === res.data.costItemId);
          }
          this.queryData = res.data;
          this.$set(this.queryData, 'proposerObj', proposerObj);
          this.setSelectData();
          // this.getCostList(this.queryData.costBelong);
          if (this.isEdit && this.isMengliDetailCost && this.linkIncomeItemNo) {
            this.getRelatedIncome(this.queryData.id);
          }
        }
      }).catch(() => {
      });
    },
    edit(params) {
      this.btnLoading = true;
      if (this.isFromSealing) params.isFromSealing = true;
      if (this.linkIncomeItemNo) params.incomeSn = this.linkIncomeItemNo;
      editCost(params).then(res => {
        this.btnLoading = false;
        if (res.code === 200) {
          this.handleClose();
          ElMessage.success('保存成功');
        } else {
          ElMessage.error(res.message);
        }
        this.$emit('submit');
      }).catch(() => {
        this.btnLoading = false;
      });
    },
    add(params) {
      this.btnLoading = true;
      createCost(params).then(res => {
        this.btnLoading = false;
        if (res.code === 200) {
          this.handleClose();
          ElMessage.success('保存成功');
        } else {
          ElMessage.error(res.message);
        }
        this.$emit('submit');
      }).catch(() => {
        this.btnLoading = false;
      });
    },
    // 根据来源获取成本项
    /* getCostList(value) {
      const params = {
        page: 1,
        perPage: 100,
        costBelong: value
      };
      costList(params).then(res => {
        if (res.data && res.data.items) {
          res.data.items.forEach(i => {
            i.value = i.costId;
            i.label = i.costName;
          });
          this.costItemOptions = res.data.items;
          if (!this.isEdit) {
            this.queryData.costItemId = '';
            // this.queryData.deductionRate = '';
          }
          if (this.$refs.costDataForm) this.$refs.costDataForm.clearValidate();
        }
      });
    }, */
    async getCostList(value) {
      const params = {
        page: 1,
        perPage: 100,
        costBelong: value
      };
      const res = await costList(params);
      if (res.data && res.data.items) {
        res.data.items.forEach(i => {
          i.value = i.costId;
          i.label = i.costName;
        });
        this.costItemOptions = res.data.items;
        if (!this.isEdit) {
          this.queryData.costItemId = '';
          // this.queryData.deductionRate = '';
        }
        if (this.$refs.costDataForm) this.$refs.costDataForm.clearValidate();
      }
    },
    // 根据成本项设置对应信息
    setCostItem(item) {
      this.selectCostItem = this.costItemOptions.find(i => i.costId === item);
      this.selectCostItem.costType = this.selectCostItem.costType ? Number(this.selectCostItem.costType) : this.selectCostItem.costType;
      this.$refs.costDataForm.clearValidate();
    },
    // 获取供应商的列表
    channelList(item) {
      return new Promise((resolve, reject) => {
        const params = { supplier: item };
        channelList(params).then(res => {
          if (res.code !== 200) reject();
          const { data } = res;
          data.forEach((i) => {
            i.label = i.value;
          });
          this.supplierList = data;
          resolve(data);
        });
      });
    },
    // 获取供应商对应的可抵扣税率
    formatDeductionRate(supplierId) {
      this.newDeductionRate = null;
      if (supplierId) {
        for (let i = 0; i < this.supplierList.length; i++) {
          if (this.supplierList[i].id === supplierId) {
            this.newDeductionRate = this.supplierList[i].discount;
            break;
          }
        }
      }
      return this.newDeductionRate;
    },
    // 供应商修改, 设置对应的可抵扣税率
    // 要区分萌力的供应商列表和销售的供应商列表
    supplierIdChange(item) {
      const { id } = item;
      if (item === '') {
        this.queryData.deductionRate = '';
        return false;
      }
      if (id) { // 萌力的供应商
        item.value = item.supplier;
        item.id = id < 0 ? '' : id;
        this.selectSupplierItem = item;
        this.queryData.deductionRate = this.selectSupplierItem.deductionRate;
        this.queryData.supplierId = item.id;
      } else {
        this.selectSupplierItem = this.supplierList.find(i => i.id === item);
        this.queryData.deductionRate = this.selectSupplierItem.discount;
      }
      this.newDeductionRate = this.selectSupplierItem.deductionRate || this.selectSupplierItem.discount;
      this.$refs.costDataForm.clearValidate();
    },
    clearSupplier() {
      this.selectSupplierItem = {};
      this.queryData.deductionRate = '';
    },
    // 可抵扣税率输入验证
    deuctiomRateInput(value) {
      this.queryData.deductionRate = percentRate(value);
    },
    // 含税成本
    taxCostChange(value) {
      this.queryData.taxCost = taxCost(value);
    },
    // 分成比例
    dividePercentInput(value) {
      this.queryData.dividePercent = percentRate(value);
    },
    // 可抵扣税率设置自动和手动
    autoDeductionRateChange(value) {
      // 自动时，修改为需获取当前所选供应商对应的可抵扣税率
      if (value) {
        this.queryData.deductionRate = this.newDeductionRate;
      }
    },
    autoDividePercentChange(v) {
      this.autoDividePercent = v;
      if (v) this.queryData.dividePercent = this.queryData.dividePercent;
    },
    resetData() {
      this.queryData = {
        autoCost: 0,
        autoDeductionRate: 1,
        deductionRate: '',
        taxCost: '',
        costType: '',
        costDescription: '',
        supplierId: '',
        platId: '',
        proposerObj: {},
        dividePercent: '',
        talentOptions: {},
        costBelong: ''
      };
      this.autoDividePercent = 1;
      this.costItemOptions = [];
      this.selectCostItem = {};
      this.selectSupplierItem = {};
      this.supplierId = '';
      this.deductionRate = '';
      this.incomeData = {
        incomeItemName: '',
        incomeDetail: '',
        unitPrice: null,
        number: null,
        totalPrice: null,
        taxRate: null,
        deliverTime: '',
        month: '',
        receivableTime: '',
        incomeTimeRange: '',
        explain: ''
      };
      this.linkIncomeItemNo = '';
    },
    // 新增供应商
    toCreateSupplier() {
      if (!this.hasRouteAuth('medium:supplier:edit')) {
        this.$message.error('暂无供应商新建权限！');
        return;
      }
      const routeUrl = this.$router.resolve({
        name: 'supplierManage',
        query: {
          toCreate: 1
        }
      });
      window.open(routeUrl.href, '_blank');
    }
  }
};
</script>

<style lang="scss" scoped>
.main {
  .width240 {
    width: 240px;
  }
  &.mobile-create-cost {
    .width240 {
      width: 200px;
    }
    .cost-form-box {
      flex-direction: column;
      overflow-x: hidden;
      overflow-y: auto;
    }
  }
  .cost-form-box {
    display: flex;
    max-height: 70vh;
    overflow: auto;
    padding-right: 6px;
    @include scrollBar($x: hidden, $y: auto, $width: 6px);
    .income-form-box {
      margin-right: 16px;
    }
    &::v-deep {
      .el-form-item {
        margin-bottom: 20px !important;
      }
    }
  }
}
.width140 {
  width: 140px;
}
.fb-switch {
  margin: 0 10px;
}
.create-cost-dialog {
  &::v-deep {
    .el-form-item {
      .select-component-withouthttp {
        width: 100%;
      }
      .el-textarea__inner {
        resize: none;
      }
    }
  }
}
.deductionRate {
  margin-right: 5px;
  color:#333;
}
.formula {
  height: 100%;
}
.max-width-300 {
  max-width: 300px;
}
.fx-icon {
  display: flex;
  align-items: center;
  height: 100%;
  z-index: 2;
  cursor: pointer;
  img {
    width: 16px;
    height: 16px;
  }
}
textarea {
  resize: none;
}
.btn-container {
  display: flex;
  justify-content: center;
  margin-top: 10px;
}
</style>
